package com.books.handler;

import com.books.model.entity.book.Books;
import com.books.model.entity.order.OrderList;
import com.books.service.book.IBookService;
import com.books.service.order.IOrderListServer;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author ZhouRui
 * @title: 码上就来
 * @projectName cbstore-spring-boot
 * @description: TODO
 * @date 2021/10/1316:23
 */

@Component
public class OrderRabbitMQFanout {

    @Autowired
    private IOrderListServer orderListServer;

    @Autowired
    private IBookService bookService;

    @Autowired
    private Books book;

    @RabbitListener(queues = "f1")
    @RabbitHandler
    public void getE1(List<OrderList> orderLists, @Headers Map<String,Object> map, Channel channel){
        for (int i = 0; i < orderLists.size(); i++) {
            orderListServer.addOrderlist(orderLists.get(i));
        }
        //手动删除rabbitmq队列中的数据的.
        if (map.get("error")!= null){
            System.out.println("错误的消息");
            try {
                channel.basicNack((Long)map.get(AmqpHeaders.DELIVERY_TAG),false,true);      //否认消息
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            channel.basicAck((Long)map.get(AmqpHeaders.DELIVERY_TAG),false);            //确认消息
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RabbitListener(queues = "f2")
    @RabbitHandler
    public void getE2(List<OrderList> orderLists, @Headers Map<String,Object> header, Channel channel){
        for (int i = 0; i < orderLists.size(); i++) {
            if(orderLists.get(i).getBuyType()==1){
                book=bookService.getById(orderLists.get(i).getProductId());
                book.setStock(book.getStock()-1);
                bookService.updateBookStock(book.getBkId(),book.getStock());
            }
            else {
                System.out.println("为电子书");
            }
        }

        //手动删除rabbitmq队列中的数据的.
        long ack = (long) header.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(ack,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
